#!/usr/bin/env node

// Probe admin access by logging in with mock user and calling admin endpoints

const axios = require('axios');

async function detectPort(ports) {
  for (const p of ports) {
    try {
      const resp = await axios.get(`http://localhost:${p}/health`, { timeout: 1000 });
      if (resp.status === 200 && resp.data && (resp.data.status === 'ok' || resp.data.success || true)) {
        return p;
      }
    } catch (_) {}
  }
  return null;
}

(async () => {
  const ports = [3000, 3001, 3011];
  const port = await detectPort(ports);
  if (!port) {
    console.error('❌ 未检测到运行中的后端(尝试端口: ' + ports.join(', ') + ')');
    process.exit(1);
  }
  console.log('✅ 检测到后端端口:', port);

  // 从环境变量或命令行读取凭据
  const email = process.env.EMAIL || process.argv[2] || 'user1@example.com';
  const password = process.env.PASSWORD || process.argv[3] || 'password1';
  console.log('👤 尝试登录用户:', email);

  // Login
  let loginRes;
  try {
    loginRes = await axios.post(`http://localhost:${port}/api/auth/login`, {
      email,
      password
    }, { timeout: 5000, headers: { 'Content-Type': 'application/json' } });
  } catch (e) {
    const data = e.response ? e.response.data : e.message;
    console.error('❌ 登录请求失败:', data);
    process.exit(2);
  }

  console.log('✅ 登录成功，状态码:', loginRes.status);
  const token = loginRes.data && loginRes.data.data && loginRes.data.data.token;
  if (!token) {
    console.error('❌ 登录响应中未找到 token:', loginRes.data);
    process.exit(3);
  }
  console.log('🔑 token 长度:', token.length);

  // 保存token到文件
  const fs = require('fs');
  fs.writeFileSync('./scripts/token.txt', token);
  console.log('💾 token已保存到 scripts/token.txt');

  const headers = { Authorization: `Bearer ${token}` };

  // admin stats
  try {
    const statsRes = await axios.get(`http://localhost:${port}/api/admin/dashboard/stats`, { headers, timeout: 5000 });
    console.log('\n[admin/dashboard/stats] 响应片段:');
    console.log(JSON.stringify(statsRes.data, null, 2).slice(0, 800));
  } catch (e) {
    console.error('\n❌ 访问 /api/admin/dashboard/stats 失败:', e.response ? e.response.data : e.message);
  }

  // admin users
  try {
    const usersRes = await axios.get(`http://localhost:${port}/api/admin/users`, { headers, timeout: 5000 });
    console.log('\n[admin/users] 响应片段:');
    console.log(JSON.stringify(usersRes.data, null, 2).slice(0, 800));
  } catch (e) {
    console.error('\n❌ 访问 /api/admin/users 失败:', e.response ? e.response.data : e.message);
  }
})();